package cc.mrbird.febs.system.service.impl;

import cc.mrbird.febs.common.authentication.JWTUtil;
import cc.mrbird.febs.system.dao.TShopTaxInfoMapper;
import cc.mrbird.febs.system.domain.TShopTaxInfo;
import cc.mrbird.febs.system.service.ITShopTaxInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dtwei
 */
@Service
public class TShopTaxInfoServiceImpl extends ServiceImpl<TShopTaxInfoMapper, TShopTaxInfo> implements ITShopTaxInfoService {

    @Override
    public void deleteByShopIds(List<String> ids) {
        LambdaQueryWrapper<TShopTaxInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(TShopTaxInfo::getShopId, ids);
        this.baseMapper.delete(queryWrapper);
    }

    @Override
    public void insertTaxInfos(List<TShopTaxInfo> taxInfos) {
        if(null != taxInfos && taxInfos.size() > 0) {
            String token = (String) SecurityUtils.getSubject().getPrincipal();
            //获取当前用户
            Map<String, String> creartInfo = new HashMap<>();
            if (StringUtils.isNotBlank(token)) {
                creartInfo.put("userName", JWTUtil.getUsername(token));
                creartInfo.put("userId", JWTUtil.getUserId(token));
            }
            //先删后加
            LambdaQueryWrapper<TShopTaxInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(TShopTaxInfo::getShopId, taxInfos.stream()
                    .filter(f -> (null != f.getShopId()) && (f.getShopId() > 0))
                    .map(TShopTaxInfo::getShopId).collect(Collectors.toList()));
            this.baseMapper.delete(queryWrapper);

            //新增区域管理员
            List<TShopTaxInfo> sts = new ArrayList<>();
            taxInfos.forEach(si -> {
                TShopTaxInfo taxTmp = new TShopTaxInfo();
                taxTmp.setShopId(si.getShopId());
                taxTmp.setTaxYear(si.getTaxYear());
                taxTmp.setTaxSum(si.getTaxSum());
                taxTmp.setCreateTime(new Date());
                taxTmp.setCreateUsername(creartInfo.get("userName"));
                taxTmp.setCreateUserId(Long.valueOf(creartInfo.get("userId")));
                sts.add(taxTmp);
            });
            this.baseMapper.insertList(sts);
        }
    }
}
